package com.veetao.api.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;

import com.veetao.api.cache.CacheClient;

/**
 * 
 * @author guohongtao
 * @date 2016年8月4日
 */

@Service
public class SyncService {

	@Resource(name="redisClient")
	private CacheClient<Jedis> cacheClient;
	
	public boolean lockWithoutRetry(String key, int lockSeconds) {
		return cacheClient.setIfNotExists(key, "1", lockSeconds);
	}
	public boolean lock(String key, int lockSeconds) {
		if(cacheClient.setIfNotExists(key, "1", lockSeconds)) {
			return true;
		}
		
		int count = 0;
		Object lock = new Object();
		while(count++ < 5) {
			if(cacheClient.setIfNotExists(key, "1", lockSeconds)){
				return true;
			}
			
			try {
				synchronized(lock) {
					lock.wait(500);
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}
	
	
	public boolean lock(String key) {
		return lock(key, 5);
	}

	public void unlock(String key) {
		cacheClient.delete(key);
	}

	public CacheClient<Jedis> getCacheClient() {
		return cacheClient;
	}

	public void setCacheClient(CacheClient<Jedis> cacheClient) {
		this.cacheClient = cacheClient;
	}

	public SyncService() {
		super();
	}


	/**
	 * @param i
	 * @author guohongtao
	 */
	public void waitMiliSeconds(int timeInMs) {
		Object lock = new Object();
		synchronized(lock) {
			try {
				lock.wait(timeInMs);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
